<!-- src/components/ThreeScene.vue -->
<template>
  <div ref="container" class="scene-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// 导入GSAP
import gsap from "gsap";
//导入dat.gui
import * as dat from "dat.gui";
//给当前组件一个名称，使用defineOptions定义
defineOptions({
  name: "ThreeScene",
});

const container = ref<HTMLElement>();
let scene: THREE.Scene;
let camera: THREE.PerspectiveCamera;
let renderer: THREE.WebGLRenderer;
let cube: THREE.Mesh;
//声明轨道控制器
let controls: OrbitControls;

let clock: THREE.Clock;
// 初始化场景
const initScene = () => {
  // 创建场景
  scene = new THREE.Scene();

  const axesHelper = new THREE.AxesHelper(10);
  scene.add(axesHelper);

  // 创建相机
  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  camera.position.z = 5;

  // 创建渲染器
  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.value?.appendChild(renderer.domElement);

  // 创建轨道控制器
  controls = new OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.05;
  // 创建一个立方体
  const geometry = new THREE.BoxGeometry();
  const material = new THREE.MeshBasicMaterial({
    color: 0x00ff00,
    // wireframe: true, // 线框模式
  });
  cube = new THREE.Mesh(geometry, material);
  //修改颜色
  material.color = new THREE.Color(0x0000ff);
  scene.add(cube);

  // 创建一个 GUI 实例
  const gui = new dat.GUI();
  gui
    .add(cube.position, "x", 0, 0)
    .min(0)
    .max(10)
    .step(0.01)
    .name("移动x轴")
    // .onChange((value) => {//实时改变
    //   console.log(value);
    // })
    .onFinishChange((value) => {
      //完全停下
      console.log(value);
    });
  //修改物体颜色
  const params = {
    color: 0x0000ff,
    fn: () => {
      gsap.to(cube.position, {
        x: 5,
        duration: 1,
        yoyo: true, // 往返运动
        repeat: -1, // 无限循环
        ease: "rough.inOut",
      });
    },
  };
  gui
    .addColor(params, "color")
    .name("颜色")
    .onChange((value) => {
      material.color.set(value);
    });
  //设置选项框
  gui.add(cube, "visible").name("是否显示");

  gui.add(params, "fn").name("执行动画");
  const folder = gui.addFolder("Cube");
  folder.add(cube.material, "wireframe").name("线框");
  // 1. 基础动画
  // const cubePosition = gsap.to(cube.position, {
  //   x: 5,
  //   duration: 1,
  //   yoyo: true, // 往返运动
  //   repeat: -1, // 无限循环
  //   ease: "rough.inOut",
  //   // delay: 3, //s
  //   onComplete: () => {
  //     console.log("动画完成", clock.getElapsedTime());
  //   },
  //   onStart: () => {
  //     console.log("动画开始", clock.getElapsedTime());
  //   },
  // });
  window.addEventListener("dblclick", () => {
    //全屏退出
    const fullscreenElement = document.fullscreenElement;
    if (fullscreenElement) {
      document.exitFullscreen();
    } else {
      renderer.domElement.requestFullscreen();
    }
    // let isActive = cubePosition.isActive();
    // if (isActive) {
    //   cubePosition.pause();
    // } else {
    //   cubePosition.resume();
    // }
  });

  // 2. 旋转动画
  // gsap.to(cube.rotation, {
  //   x: Math.PI * 2,
  //   y: Math.PI * 2,
  //   duration: 4,
  //   repeat: -1,
  //   ease: "none",
  // });

  // 3. 缩放动画
  gsap.to(cube.scale, {
    x: 2,
    y: 2,
    z: 2,
    duration: 1,
    delay: 1,
    // yoyo: true,
    // repeat: -1,
    ease: "power2.inOut",
  });
  // gsap.to(cube.scale, {
  //   x: 1,
  //   y: 1,
  //   z: 1,
  //   duration: 1,
  //   delay: 3,
  //   // yoyo: true,
  //   // repeat: -1,
  //   ease: "power2.inOut",
  // });
  // // 添加环境光
  // const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
  // scene.add(ambientLight);
  // //

  // // 添加平行光
  // const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
  // directionalLight.position.set(0, 1, 0);
  // scene.add(directionalLight);

  //使用Clock
  clock = new THREE.Clock();
  console.log(clock.getElapsedTime());
  // 开始动画循环
  animate();
};

// 动画循环
const animate = () => {
  requestAnimationFrame(animate);
  controls.update();
  renderer.render(scene, camera);
};

// 处理窗口大小变化
const handleResize = () => {
  if (!container.value) return;

  camera.aspect = window.innerWidth / window.innerHeight;
  //设备像素比

  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // 设置设备像素比
};

// 组件挂载时初始化场景
onMounted(() => {
  initScene();
  window.addEventListener("resize", handleResize);
});

// 组件卸载时清理资源
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  // 清理 Three.js 资源
  scene.remove(cube);
  renderer.dispose();
});
</script>

<style scoped lang="less">
.scene-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #000;
}
</style>
